<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add="addFn" :list="list"></TodoHeader>
    <TodoMain @delFn="delTask" :showList="showList"></TodoMain>
    <TodoFooter
      @changType="tyepfn"
      :selected="sel"
      :len="list.length"
      @clearList="clearFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css";
import "./styles/index.css";

import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";

export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // list: [
      //   { id: 100, name: "吃饭", isDone: true },
      //   { id: 101, name: "睡觉", isDone: false },
      //   { id: 102, name: "打豆豆", isDone: true },
      // ],
      list: JSON.parse(localStorage.getItem("list")) || [],
      sel: "all",
    };
  },
  methods: {
    addFn(value) {
      this.list.push({
        id: this.list.length ? this.list.at(-1).id + 1 : 100,
        name: value,
        isDone: false,
      });
    },
    delTask(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    tyepfn(val) {
      this.sel = val;
    },
    clearFn() {
      this.list = this.list.filter((item) => !item.isDone);
    },
  },
  computed: {
    showList() {
      if (this.sel === "all") {
        return this.list;
      } else if (this.sel === "yes") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list.filter((item) => !item.isDone);
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("list", JSON.stringify(this.list));
        // console.log(JSON.parse(localStorage.getItem("list")));
      },
      immediate: true,
    },
  },
};
</script>